package com.dh.blog.controllers;

import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.xml.ws.BindingType;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.dh.blog.handler.SaveFileHandler;
import com.dh.blog.service.BlogService;
import com.dh.blog.service.FileService;
import com.dh.blog.service.UserService;
import com.dh.blog.vo.SimpleFileVo;
import com.dh.blog.vo.UserVo;
import com.ewei.web.common.exception.MessageRuntimeException;
import com.ewei.web.common.http.HttpUtils;
import com.ewei.web.common.json.resolver.JsonModel;
import com.ewei.web.common.response.ResponseVO;
import com.ewei.web.common.utils.FileToolsBar;
import com.ewei.web.common.validator.SaveGroup;
import com.mysql.jdbc.StringUtils;

@RequestMapping("/user")
@Controller
public class UserController {
	private static final Logger logger = LogManager.getLogger(UserController.class);
	private static final String FILE_PATH_PATTERN = "[\\s\\S]*(?=/)";
	@Resource(name="userService")
	private UserService userService;
	@Resource
	private Properties config;
	@Resource
	private SaveFileHandler saveFile;
	@Resource(name="fileService")
	private FileService fileService;
	@RequestMapping({"/login"})
	public void login(@Valid UserVo user,BindingResult result){
		
	}
	/**
	 * 用户注册
	 */
	@RequestMapping(value="/register",method=RequestMethod.POST)
	@ResponseBody
	public Object register(@JsonModel @Validated(value=SaveGroup.class) UserVo user,BindingResult result){
		if(result.hasErrors()){
			return new ResponseVO().resolveError(result);
		}
		if(null != userService.getByLoginName(user.getLoginName())){
			return new ResponseVO().error("201", config.get("201"));
		}
		if(userService.isExistBlog(user.getPath())){
			return new ResponseVO().error("202",config.get("202"));
		}
		Pattern pattern = Pattern.compile(FILE_PATH_PATTERN);
		String tempPath = user.getPicpath();
		Matcher matcher = pattern.matcher(tempPath);
		String toPath = "";
		String picDir = config.getProperty("user_pic_dir");
		boolean exist = !StringUtils.isNullOrEmpty(picDir);
		if(exist&&matcher.find()){
			toPath = matcher.replaceFirst(picDir);
		}else if(exist){
			toPath = picDir + "/"+tempPath;
		}else{
			toPath = tempPath;
		}
		user.setPicpath(toPath);
		userService.doRegister(user);
		saveFile.transfer(tempPath,toPath);
		return new ResponseVO();
	}
	/**
	 * 注册上传图片接口（图片上传超过12小时，由后台定时任务删除）
	 * @return
	 */
	@RequestMapping(value="/upload",method=RequestMethod.POST)
	@ResponseBody
	public Object uploadPic(@RequestParam(value="pic",required=true)
		MultipartFile loadFile,HttpServletRequest request,HttpServletResponse response){
		if(null != loadFile && !loadFile.isEmpty()){
			long current0 = System.currentTimeMillis();
			InputStream in = null;
			String path = null;
			try{
				in = loadFile.getInputStream();
				path = saveFile.saveByDir(in
						,config.getProperty("upload_dir"));
			}catch(IOException io){
				throw new MessageRuntimeException(io);
			}
			SimpleFileVo fileVo = new SimpleFileVo(path,
					Calendar.getInstance().getTime(),1);
			try{
				fileService.doSaveSysFile(fileVo);
			}catch(Exception ex){
				logger.info("deleting uploaded file.... path is "+path);
				saveFile.remove(path);
				throw new MessageRuntimeException(ex);
			}finally{
			}
			System.out.println(System.currentTimeMillis()-current0);
			String cookieName = config.getProperty("upload_cookie_name");
			if(null != cookieName){//将文件path信息压缩写入cookie
				Cookie cookie = HttpUtils.umpressCookie(request, cookieName);//检验cookie是否已经存在
				if(null != cookie){//删除原有的cookie，同时删除旧文件
					String value = cookie.getValue();
					try{
						saveFile.remove(value);
					}catch(Exception ex){//保证程序正常执行
						if(logger.isInfoEnabled()){
							logger.info(ex);
						}
					}
				}else{
					cookie = new Cookie(cookieName, null);
				}
				cookie.setValue(path);
				HttpUtils.compressCookie(response, cookie);//cookie压缩并写入rsponse
			}
			System.out.println(System.currentTimeMillis()-current0);
			return new ResponseVO().setDatas(fileVo);
		}
		return new ResponseVO().error("203",config.get("203"));
	}
}
